/**
 * Retrieves the translation of text.
 *
 * @see https://developer.wordpress.org/block-editor/reference-guides/packages/packages-i18n/
 */
import { __ } from "@wordpress/i18n";

/**
 * React hook that is used to mark the block wrapper element.
 * It provides all the necessary props like the class name.
 *
 * @see https://developer.wordpress.org/block-editor/reference-guides/packages/packages-block-editor/#useblockprops
 */
import { useBlockProps, RichText } from "@wordpress/block-editor";

/**
 * Lets webpack process CSS, SASS or SCSS files referenced in JavaScript files.
 * Those files can contain any CSS code that gets applied to the editor.
 *
 * @see https://www.npmjs.com/package/@wordpress/scripts#using-css
 */
import "./editor.scss";

/**
 * The edit function describes the structure of your block in the context of the
 * editor. This represents what the editor will render when the block is used.
 *
 * @see https://developer.wordpress.org/block-editor/reference-guides/block-api/block-edit-save/#edit
 *
 * @return {Element} Element to render.
 */

import { useState } from "react";
const codeData = [
	{
		text: "文章列表",
		code: '[past_posts_display ids="文章ID,文章ID" limit="10"]',
		desdescribe: "插入文章列表，limit控制数量",
	},
	{
		text: "复制按钮",
		code: '[mabox_copy_btn name="按钮名称" alert="弹窗内容" link="跳转网址"]待复制文本[/mabox_copy_btn]',
		desdescribe: "点击按钮可复制提供的内容并弹窗提示，若提供链接会跳转至链接处",
	},
];
export default function Edit({ attributes, setAttributes }) {
	const blockProps = useBlockProps();

	const onChangeContent = (newContent) => {
		setAttributes({ content: newContent });
	};

	//点击按钮出现描述
	const [activeIndex, setActiveIndex] = useState(0); // 默认显示第一个描述

	const handleClick = (index) => {
		setActiveIndex(index);
	};

	const btn = (index) => {
		handleClick(index);
		//传值
		const newContent = codeData[index].code;
		//console.log(newContent);
		setAttributes({ content: newContent });
	};

	return (
		<div {...useBlockProps()}>
			<div className="components-placeholder block-editor">
				<label class="components-placeholder__label">
					<i class="dashicon dashicons dashicons-shortcode "></i>
					[/] MaBox 插件短代码
				</label>
				<RichText
					tagName="textarea"
					className="block-editor-plain-text block-editor-plain-text blocks-shortcode__textarea"
					onChange={onChangeContent}
					allowedFormats={["core/bold", "core/italic"]}
					value={attributes.content}
					placeholder={__("填写短代码内容", "mabox-copy-btn")}
				/>

				{codeData.map((item, index) => (
					<p
						key={index}
						className="desc"
						style={{ display: activeIndex === index ? "block" : "none" }}
					>
						{item.desdescribe}
					</p>
				))}

				<div className="btn">
					{codeData.map((item, index) => (
						<button key={index} onClick={() => btn(index)}>
							{item.text}
						</button>
					))}
				</div>
			</div>
		</div>
	);
}
